﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Web;
using System.Drawing;
using System.Drawing.Drawing2D;

namespace IHISCETeim.Library
{
    public class FileUploadHelper
    {

        /// <summary>
        /// 获取指定大小的文件（压缩）
        /// </summary>
        /// <param name="sourcefullname">原图片路径</param>
        /// <param name="dispMaxWidth">要显示的大小的宽</param>
        /// <param name="dispMaxHeight">要显示的大小的高</param>
        public static string GetSmallPic(string sourcefullname, int dispMaxWidth, int dispMaxHeight)
        {
            try
            {              
                FileInfo f = new System.IO.FileInfo(sourcefullname);
                string output = f.DirectoryName;
                output = output + @"\small\";              
                string newfilename = Path.Combine(output, string.Format("{0}_{1}_{2}", dispMaxWidth, dispMaxHeight, Path.GetFileName(sourcefullname)));
                if (File.Exists(newfilename))
                    return newfilename;
                if (!Directory.Exists(output))
                    Directory.CreateDirectory(output);
                Bitmap mg = new Bitmap(sourcefullname);
                Size newSize = new Size(dispMaxWidth, dispMaxHeight);
                Bitmap bp = ResizeImage(mg, newSize);
                if (bp != null)
                    bp.Save(newfilename, System.Drawing.Imaging.ImageFormat.Jpeg);

                return newfilename;
            }
            catch (Exception exc)
            {
               // HttpContext.Current.Response.Write(exc.Message);
                return sourcefullname;
            }

        }
        private static Bitmap ResizeImage(Bitmap mg, Size newSize)
        {
            double ratio = 0d;
            double myThumbWidth = 0d;
            double myThumbHeight = 0d;
            int x = 0;
            int y = 0;

            Bitmap bp;

            if ((mg.Width / Convert.ToDouble(newSize.Width)) > (mg.Height /
            Convert.ToDouble(newSize.Height)))
                ratio = Convert.ToDouble(mg.Width) / Convert.ToDouble(newSize.Width);
            else
                ratio = Convert.ToDouble(mg.Height) / Convert.ToDouble(newSize.Height);
            myThumbHeight = Math.Ceiling(mg.Height / ratio);
            myThumbWidth = Math.Ceiling(mg.Width / ratio);

            Size thumbSize = new Size((int)newSize.Width, (int)newSize.Height);
            bp = new Bitmap(newSize.Width, newSize.Height);
            x = (newSize.Width - thumbSize.Width) / 2;
            y = (newSize.Height - thumbSize.Height);
            System.Drawing.Graphics g = Graphics.FromImage(bp);
            g.SmoothingMode = SmoothingMode.HighQuality;
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;
            g.PixelOffsetMode = PixelOffsetMode.HighQuality;
            Rectangle rect = new Rectangle(x, y, thumbSize.Width, thumbSize.Height);
            g.DrawImage(mg, rect, 0, 0, mg.Width, mg.Height, GraphicsUnit.Pixel);

            return bp;

        }
        /// <summary>
        ///  上传文件
        /// </summary>
        /// <param name="folderpath">需存放的文件夹名称，不包含网站所在的根目录</param>
        /// <param name="fileExtension">允许上传的文件后缀</param>
        /// <returns>返回上传文件所在的实际目录</returns>
        static public string UpLoadExcel(string folderpath)
        {
            HttpFileCollection files = HttpContext.Current.Request.Files;
            /// '状态信息
            System.Text.StringBuilder strMsg = new System.Text.StringBuilder("");
           // strMsg.Append("上传的文件分别是：<hr color='red'/>");
            try
            {
                string fileName = "", fileExtension = "";
                for (int iFile = 0; iFile < files.Count; iFile++)
                {
                    ///'检查文件扩展名字
                    HttpPostedFile postedFile = files[iFile];
                    fileName = System.IO.Path.GetFileName(postedFile.FileName);
                    if (fileName != "")
                    {
                        fileExtension = System.IO.Path.GetExtension(fileName);
                        if (fileExtension.IndexOf("xls") < 0)
                            return "";//
                    }
                    //是否已存在
                    if (File.Exists(System.Web.HttpContext.Current.Request.MapPath(folderpath + "/") + fileName))
                    {
                        File.Delete(System.Web.HttpContext.Current.Request.MapPath(folderpath + "/") + fileName);
                    }
                    
                    if (fileName != "")
                    {
                        if (!Directory.Exists(System.Web.HttpContext.Current.Request.MapPath(folderpath)))
                            Directory.CreateDirectory(System.Web.HttpContext.Current.Request.MapPath(folderpath));


                        postedFile.SaveAs(System.Web.HttpContext.Current.Request.MapPath(folderpath + "/") + fileName);
                    }
                }
                //strStatus.Text = strMsg.ToString();
                return System.Web.HttpContext.Current.Request.MapPath(folderpath + "/") + fileName;
            }
            catch (System.Exception Ex)
            {
                //strStatus.Text = Ex.Message;
                return "";
            }


        }


        static string jsonString(string str)
        {
            str = str.Replace("\\", "\\\\");
            str = str.Replace("/", "\\/");
            str = str.Replace("'", "\\'");
            return str;
        }


        static string GetFileExt(string FullPath)
        {
            if (FullPath != "") return FullPath.Substring(FullPath.LastIndexOf('.') + 1).ToLower();
            else return "";
        }

        static void CreateFolder(string FolderPath)
        {
            if (!System.IO.Directory.Exists(FolderPath)) System.IO.Directory.CreateDirectory(FolderPath);
        }
    }
}
